﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace THenu.TinyHourseLib.DesignPattern.Creational_Patterns.Singleton_Pattern
{
    class SingletonPattern:IPatternDemonstrate
    {
        public void StructuralCode()
        {
            // Constructor is protected -- cannot use new
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            // Test for same instance
            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }
        }

        public string PatternDescription()
        {
            string strDescription = @"Definition
Ensure a class has only one instance and provide a global point of access to it.
Participants

    The classes and objects participating in this pattern are:

Singleton   (LoadBalancer)
·defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
·responsible for creating and maintaining its own unique instance.
";
            return strDescription;
        }

        public void RealWorldExample()
        {
            LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

            // Same instance?
            if (b1 == b2 && b2 == b3 && b3 == b4)
            {
                Console.WriteLine("Same instance\n");
            }

            // Load balance 15 server requests
            LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            for (int i = 0; i < 15; i++)
            {
                string server = balancer.Server;
                Console.WriteLine("Dispatch Request to: " + server);
            }
        }
    }
}
